import { login, getInfo } from '@/api/login'
import { setToken } from '@/utils/auth'

const user = {

    state: {
        token: '',
        roles: [],
    },
    mutations: {
        SET_TOKEN: (state, token) => {
            state.token = token
        },
        SET_ROLES: (state, roles) => {
            state.roles = roles
        }
    },
    actions: {
        Login( { commit }, userInfo) {

            const username = userInfo.username.trim()
            const password = userInfo.password
            const code = userInfo.code
            const uuid = userInfo.uuid

            console.log('action Login ' + username + ' ' + password )

            return new Promise((resolve) => {
                login(username, password, code, uuid).then(res => {
                    console.log(res.token)
                    setToken(res.token)
                    commit('SET_TOKEN', res.token)
                    resolve()
                })
            })

        },
        GetInfo({ commit, state }) {
            console.log('store user getinfo')
            return new Promise((resolve) => {
                getInfo(state.token).then(res => {
                    //const user = res.user
                    if (res.roles && res.roles.length > 0) {
                        commit('SET_ROLES', res.roles)
                    } else {
                        commit('SET_ROLES', ['ROLE_DEFAULT'])
                    }
                    resolve(res)
                })
            })
        }
    }
}

export default user
